package com.appcenter.application.service;

import com.appcenter.application.dto.apps.AppDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.app.*;
import com.appcenter.application.input.permission.GetPermissionsServiceInput;
import com.appcenter.application.mapper.AppsMapper;
import com.appcenter.application.mapper.PermissionsMapper;
import com.appcenter.application.model.Apps;
import com.appcenter.application.model.Permissions;
import com.appcenter.application.model.Users;
import com.appcenter.application.output.app.*;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.http.util.TextUtils.isBlank;

@Service
public class AppService {
    @Autowired
    AppsMapper appMapper;
    @Autowired
    PermissionsMapper prmissionMapper;

    @Autowired
    PermissionService permissionService;

    @Autowired
    ObjectFinal objectFinal;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//    @Transactional

    /**
     *  创建人:Coke
     *  备注:创建应用
     *  时间: 2019/4/26 12:19
     *  参数:
     */
    public CreateAppOutput CreateApp(CreateAppInput input) throws Exception {
        CreateAppOutput output = new CreateAppOutput();
        int AppCodeCount=appMapper.GetAllAppsByAppCode(input.getItem().getAppCode()).size();
        if (AppCodeCount > 0)
            throw new ErrorJsonResult("1000031","应用编号已存在！");
        int appNameCount=appMapper.GetAllAppsByAppName(input.getItem().getAppName()).size();

        if (appNameCount > 0)
            throw new ErrorJsonResult("1000031","应用名称已存在！");

        Apps app = new Apps();
        BeanUtils.copyProperties(input.getItem(),app);
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        app.setId(uuid);
        app.setUseHrOrg(true);
        app.setValidStatus(true);
        app.setCreateTime(new Date());
        app.setCreateUserId(CurrentUser.getUserId());
        BusinessLogger.Info(LoggerGenre.Add,"添加应用",input);

        appMapper.insertSelective(app);
        //同时创建一个应用权限   应用权限的Id 和 apps的Id保持一致
        Example examplePer = new Example(Permissions.class);
        Example.Criteria criteria = examplePer.createCriteria();
        criteria.andEqualTo("permissionType", "应用");
        criteria.andIsNull("parentId");
        criteria.andEqualTo("validStatus", 1);

        Permissions  parentPermission = prmissionMapper.selectOneByExample(examplePer);
        Permissions permission=new  Permissions();
        permission.setId(uuid);
        permission.setPermissionCode(app.getAppCode());
        permission.setPermissionName(app.getAppName());
        permission.setValidStatus(true);
        permission.setVisible(true);
        permission.setPermissionType("应用");
        permission.setListOrder(app.getOrderList());
        permission.setLevel(parentPermission.getLevel()+1);
        permission.setCreateTime(new Date());
        permission.setCreateUserId(CurrentUser.getUserId());
        permission.setValidStatus(true);
        permission.setParentId(parentPermission.getId());
        permission.setIdPath(parentPermission.getId()+"/"+uuid);
        prmissionMapper.insertSelective(permission);

        //添加该应用的菜单权限
        Permissions menuPermission=new  Permissions();
        uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        menuPermission.setId(uuid);
        menuPermission.setAppId(permission.getId());
        menuPermission.setPermissionCode("菜单");
        menuPermission.setPermissionName("菜单");
        menuPermission.setListOrder(1L);
        menuPermission.setLevel(1L);
        menuPermission.setCreateUserId(CurrentUser.getUserId());
        menuPermission.setCreateTime(new Date());
        menuPermission.setValidStatus(true);
        menuPermission.setIdPath(uuid);
        menuPermission.setVisible(true);
        menuPermission.setPermissionType("菜单");

        prmissionMapper.insertSelective(menuPermission);

        AppDto item = new AppDto();
        BeanUtils.copyProperties(app,item);
        output.setItem(item);
        return output;
    }
//    @CacheEvict(cacheNames="basewarrant", allEntries=true)
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 删除应用
     *  时间: 2019/4/26 12:19
     *  参数:
     */
    public DeleteAppOutput DeleteApp(DeleteAppInput input) throws Exception {
        DeleteAppOutput output = new DeleteAppOutput();
        Apps oldApps=appMapper.selectByPrimaryKey(input.getItem().getId());
        oldApps.setValidStatus(false);
        appMapper.updateByPrimaryKey(oldApps);
        BusinessLogger.Info(LoggerGenre.Delete,"删除应用",input);
        //同时删除应用权限
        prmissionMapper.deleteByPrimaryKey(oldApps.getId());
        return output;
    }
//    @CacheEvict(cacheNames="basewarrant", allEntries=true)
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 修改应用
     *  时间: 2019/4/26 12:20
     *  参数:
     */
    public EditAppOutput EditApp(EditAppInput input) throws Exception {
        EditAppOutput output=new EditAppOutput();
        int AppCodeCount=appMapper.GetAllAppsByAppCodeNoId(input.getItem().getAppCode(),input.getItem().getId()).size();
        if (AppCodeCount > 0)
            throw new ErrorJsonResult("1000031","应用编号已存在！");
        int AppNameCount=appMapper.GetAllAppsByAppNameNoId(input.getItem().getAppName(),input.getItem().getId()).size();
        if (AppNameCount > 0)
            throw new ErrorJsonResult("1000031","应用名称已存在！");
        Apps oldApp= appMapper.selectByPrimaryKey(input.getItem().getId());
        BeanUtils.copyProperties(input.getItem(),oldApp);
        BusinessLogger.Info(LoggerGenre.Update,"修改应用",input);

        appMapper.updateByPrimaryKey(oldApp);

        //同时修改该应用的权限信息
       Permissions oldPermission= prmissionMapper.selectByPrimaryKey(oldApp.getId());
        oldPermission.setPermissionCode(oldApp.getAppCode());
        oldPermission.setPermissionName(oldApp.getAppName());
        oldPermission.setListOrder(oldApp.getOrderList());
        prmissionMapper.updateByPrimaryKey(oldPermission);

        AppDto item = new AppDto();
        BeanUtils.copyProperties(oldApp,item);
        output.setItem(item);
        return  output;
    }
//    @Transactional
    //@Cacheable(value="apps", key = "#input.userCode")
    /**
     *  创建人:Coke
     *  备注: 获取应用
     *  时间: 2019/4/26 12:20
     *  参数:
     */
    public GetAppsOutput GetApps(GetAppsInput input) throws Exception {
        GetAppsOutput output = new GetAppsOutput();
        input.setAppCode(ObjectFinal.APP_CODE);
        input.setUserCode(CurrentUser.getUserCode());
        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize());
        List<Apps> ls = appMapper.GetApps(input);
        PageInfo<Apps> page = new PageInfo<>(ls);
        List<AppDto> newls = new ArrayList<AppDto>();
        for (int i = 0; i < ls.size(); i++) {
            AppDto appDto=new AppDto();
            BeanUtils.copyProperties(ls.get(i), appDto);
            newls.add(appDto);
        }
        BusinessLogger.Info(LoggerGenre.View,"获取应用",input);
        output.setItems(new PagedResult<AppDto>(newls, (int)page.getTotal()));
        return  output;
    }


    /**
     *  创建人:Coke
     *  备注: 获取全部应用
     *  时间: 2019/4/26 12:20
     *  参数:
     */
    public GetAppsOutput GetAllApps(GetAppsInput input) throws Exception {
        GetAppsOutput output = new GetAppsOutput();
        input.setAppCode(ObjectFinal.APP_CODE);
        input.setUserCode(CurrentUser.getUserCode());
        List<Apps> ls = appMapper.GetApps(input);
        PageInfo<Apps> page = new PageInfo<>(ls);
        List<AppDto> newls = new ArrayList<AppDto>();
        for (int i = 0; i < ls.size(); i++) {
            AppDto appDto=new AppDto();
            BeanUtils.copyProperties(ls.get(i), appDto);
            newls.add(appDto);
        }
        BusinessLogger.Info(LoggerGenre.View,"获取应用",input);
        output.setItems(new PagedResult<AppDto>(newls, (int)page.getTotal()));
        return  output;
    }



    /**
     *  创建人:Coke
     *  备注: 加载应用
     *  时间: 2019/4/26 13:42
     *  参数:
     */
//    @Transactional
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();
        output.setItems(GetApps(input).getItems());
        return output;
    }
}
